package com.weilx959.spt.core.component;

import com.jfoenix.controls.JFXTextField;
import com.jfoenix.validation.base.ValidatorBase;
import com.weilx959.spt.core.utils.FXMLUtil;
import com.weilx959.spt.core.utils.Try;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 文本输入框表单项控件
 *
 * @author weilx
 * @since 2024-05-29
 */
@Slf4j
public class TextFieldFormItemControl extends ValidatorFormItemControl<String> {
    private static final String XML = "/assets/fxml/component/text-field-form-control.fxml";

    @FXML
    private Label labelControl;

    @FXML
    private JFXTextField textFieldControl;

    public TextFieldFormItemControl() {
        super();
        initialize();
    }

    @Override
    public Try<String> validate() {
        return Try.of(() -> {
            if (!textFieldControl.validate()) {
                throw new IllegalStateException(textFieldControl.getActiveValidator().getMessage());
            }
        });
    }

    @Override
    public boolean isModified() {
        return !StringUtils.equals(oldValue, getValue());
    }

    @Override
    public void addValidator(ValidatorBase... validator) {
        this.textFieldControl.setValidators(validator);
    }

    public EventHandler<ActionEvent> getOnAction() {
        return textFieldControl.getOnAction();
    }

    public void setOnAction(EventHandler<ActionEvent> onAction) {
        textFieldControl.setOnAction(onAction);
    }


    private void initialize() {
        // load
        FXMLUtil.loadControl(this, XML);
        // 输入框
        textFieldControl.textProperty().bindBidirectional(valueProperty());
    }

    // builder
    public static TextFieldFormItemControlBuilder builder() {
        return new TextFieldFormItemControlBuilder();
    }

    public static class TextFieldFormItemControlBuilder
        extends ValidatorFormItemControlBuilder<String, TextFieldFormItemControl, TextFieldFormItemControlBuilder> {
        @Override
        protected TextFieldFormItemControl newFormItemControl() {
            return new TextFieldFormItemControl();
        }

        @Override
        protected TextFieldFormItemControlBuilder self() {
            return this;
        }
    }
}
